﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;

namespace IRC.IRepairClouds.WebClient.BasePages
{
    public class BasePage : System.Web.UI.Page, IScriptControl
    {
        private DummyPageStatePersister _pageStatePersister;
        private ScriptManager _scriptManager;

        public BasePage()
        {
        }

        public virtual bool DisableViewstateCompletely
        {
            get { return false; }
        }

        public virtual bool RegisterIScripts
        {
            get { return false; }
        }

        public virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            throw new InvalidOperationException("Override with your own implementation.");
        }

        public virtual IEnumerable<ScriptReference> GetScriptReferences()
        {
            throw new InvalidOperationException("Override with your own implementation.");
        }

        protected override System.Web.UI.PageStatePersister PageStatePersister
        {
            get
            {
                if (DisableViewstateCompletely)
                {
                    if (_pageStatePersister == null)
                        _pageStatePersister = new DummyPageStatePersister(this);
                    return _pageStatePersister;
                }
                else
                    return base.PageStatePersister;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (RegisterIScripts)
            {
                if (!this.DesignMode)
                {
                    _scriptManager = ScriptManager.GetCurrent(this);
                    if (_scriptManager == null)
                        throw new HttpException("A ScriptManager control must exist on the current page.");
                    _scriptManager.RegisterScriptControl(this);
                }
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (RegisterIScripts)
            {
                if (!this.DesignMode)
                    _scriptManager.RegisterScriptDescriptors(this);
            }
            base.Render(writer);
        }

        public static void AuthInsufficientPermissions()
        {
            Auth.InsufficientPermissions();
        }

        public static void AuthInsufficientDataPermissions()
        {
            Auth.InsufficientDataPermissions();
        }

        public static void AuthInsufficientFilePermissions()
        {
            Auth.InsufficientFilePermissions();
        }
    }
}